<?php
/*
 * @ https://EasyToYou.eu - IonCube v11 Decoder Online
 * @ PHP 7.2 & 7.3
 * @ Decoder version: 1.1.6
 * @ Release: 10/08/2022
 */

// Decoded file for php version 71.
namespace longbingcore\wxcore;

class WxPay
{
    protected static $uniacid;
    public function __construct($uniacid)
    {
        self::$uniacid = $uniacid;
    }
    public function payConfig()
    {
        $uniacid_id = self::$uniacid;
        $pay = \think\facade\Db::name("longbing_card_config_pay")->where(["uniacid" => $uniacid_id])->find();
        $config = \think\facade\Db::name("longbing_card_config")->where(["uniacid" => $uniacid_id])->find();
        if(empty($pay["mch_id"]) || empty($pay["pay_key"])) {
            return ["result_code" => false, "return_code" => false, "err_code_des" => "未配置支付信息"];
        }
        $setting["payment"]["merchant_id"] = $pay["mch_id"];
        $setting["payment"]["key"] = $pay["pay_key"];
        $setting["payment"]["cert_path"] = $pay["cert_path"];
        $setting["payment"]["key_path"] = $pay["key_path"];
        $setting["app_id"] = $config["appid"];
        $setting["secret"] = $config["app_secret"];
        $setting["company_pay"] = $config["company_pay"];
        return $setting;
    }
    public function crteateMchPay($paymentApp, $openid, $money = "", $order_code = "")
    {
        if($paymentApp["company_pay"] == 2) {
            $res = $this->crteateMchPayV2($paymentApp, $openid, $money, $order_code);
            return $res;
        }
        $money = $money * 100;
        $payid = substr(md5("longbing666" . time()), 0, 11);
        if(empty($paymentApp["app_id"]) || empty($paymentApp["payment"]["merchant_id"])) {
            return $paymentApp;
        }
        if(empty($openid)) {
            return ["result_code" => false, "return_code" => false, "err_code_des" => "用户信息错误"];
        }
        $setting["mini_appid"] = $paymentApp["app_id"];
        $setting["mini_appsecrept"] = $paymentApp["secret"];
        $setting["mini_mid"] = $paymentApp["payment"]["merchant_id"];
        $setting["mini_apicode"] = $paymentApp["payment"]["key"];
        $setting["apiclient_cert"] = $paymentApp["payment"]["cert_path"];
        $setting["apiclient_cert_key"] = $paymentApp["payment"]["key_path"];
        define("WX_APPID", $setting["mini_appid"]);
        define("WX_MCHID", $setting["mini_mid"]);
        define("WX_KEY", $setting["mini_apicode"]);
        define("WX_APPSECRET", $setting["mini_appsecrept"]);
        define("WX_SSLCERT_PATH", $setting["apiclient_cert"]);
        define("WX_SSLKEY_PATH", $setting["apiclient_cert_key"]);
        define("WX_CURL_PROXY_HOST", "0.0.0.0");
        define("WX_CURL_PROXY_PORT", 0);
        define("WX_REPORT_LEVENL", 0);
        require_once PAY_PATH . "weixinpay/lib/WxPay.Api.php";
        require_once PAY_PATH . "weixinpay/example/WxPay.JsApiPay.php";
        require_once PAY_PATH . "weixinpay/lib/WxMchPay.php";
        $payClass = new \WxMchPay();
        $res = $payClass->MchPayOrder($openid, $money, $payid);
        return $res;
    }
    public function crteateMchPayV2($paymentApp, $openid, $money, $user_name = "")
    {
        $out_trade_no = time() . rand(1000, 9999);
        $url = "https://api.mch.weixin.qq.com/v3/transfer/batches";
        $pars = [];
        $order_code = "sjzz" . time() . mt_rand(10000, 99999);
        $pars["appid"] = $paymentApp["app_id"];
        $pars["out_batch_no"] = $order_code;
        $pars["batch_name"] = "商家转账";
        $pars["batch_remark"] = "商家转账";
        $pars["total_amount"] = intval($money * 100);
        $pars["total_num"] = 1;
        $pars["transfer_detail_list"][0] = ["out_detail_no" => $order_code, "transfer_amount" => $pars["total_amount"], "transfer_remark" => "商家转账", "openid" => $openid];
        $Wechatpay = 0;
        if(200000 <= $pars["total_amount"] && !empty($user_name)) {
            $pars["transfer_detail_list"][0]["user_name"] = $this->getEncrypt($user_name, $paymentApp);
            $Wechatpay = 1;
        }
        $token = $this->getToken($pars, $paymentApp);
        $res = $this->http_post($url, json_encode($pars), $token, $paymentApp, $Wechatpay);
        $resArr = json_decode($res, true);
        if(!empty($resArr["code"])) {
            $resArr["return_code"] = "fail";
            $resArr["result_code"] = $resArr["return_code"];
            $resArr["err_code_des"] = $resArr["message"];
        } else {
            $resArr["return_code"] = "SUCCESS";
            $resArr["result_code"] = $resArr["return_code"];
        }
        return $resArr;
    }
    public function getEncrypt($str, $paymentApp)
    {
        $public_key_path = $paymentApp["payment"]["wx_certificates"];
        if(empty($public_key_path)) {
            return "";
        }
        $public_key = file_get_contents($public_key_path);
        $encrypted = "";
        if(openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
            $sign = base64_encode($encrypted);
            return $sign;
        }
        throw new Exception("encrypt failed");
    }
    public function getMchPayRecord($order_code, $paymentApp)
    {
        $url = "https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no/" . $order_code . "/details/out-detail-no/" . $order_code;
        $token = $this->getToken([], $paymentApp, "GET", $url);
        $res = $this->https_request($url, [], $token);
        $resArr = json_decode($res, true);
        return $resArr;
    }
    public function https_request($url, $data, $token)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, (string) $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $headers = ["Authorization:WECHATPAY2-SHA256-RSA2048 " . $token, "Accept: application/json", "Content-Type: application/json; charset=utf-8", "User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"];
        if(!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    public function get_Certificates($paymentApp)
    {
        $platformCertificateFilePath = $paymentApp["payment"]["wx_certificates"];
        if(empty($platformCertificateFilePath)) {
            return "";
        }
        $a = openssl_x509_parse(file_get_contents($platformCertificateFilePath));
        return !empty($a["serialNumberHex"]) ? $a["serialNumberHex"] : "";
    }
    private function http_post($url, $data, $token, $paymentApp, $Wechatpay = 0)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, (string) $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $headers = ["Authorization:WECHATPAY2-SHA256-RSA2048 " . $token, "Accept: application/json", "Content-Type: application/json; charset=utf-8", "User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"];
        if($Wechatpay == 1) {
            $certificates = $this->get_Certificates($paymentApp);
            $headers[] = "Wechatpay-Serial:" . $certificates;
        }
        if(!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    public function getToken($pars, $paymentApp, $http_method = "POST", $usrl_data = "")
    {
        $url = !empty($usrl_data) ? $usrl_data : "https://api.mch.weixin.qq.com/v3/transfer/batches";
        $timestamp = time();
        $url_parts = parse_url($url);
        $nonce = $timestamp . rand(10000, 99999);
        $body = !empty($pars) ? json_encode((object) $pars) : "";
        $stream_opts = ["ssl" => ["verify_peer" => false, "verify_peer_name" => false]];
        $apiclient_cert_path = $paymentApp["payment"]["cert_path"];
        $apiclient_key_path = $paymentApp["payment"]["key_path"];
        $apiclient_cert_arr = openssl_x509_parse(file_get_contents($apiclient_cert_path, false, stream_context_create($stream_opts)));
        $serial_no = $apiclient_cert_arr["serialNumberHex"];
        $mch_private_key = file_get_contents($apiclient_key_path, false, stream_context_create($stream_opts));
        $merchant_id = $paymentApp["payment"]["merchant_id"];
        $canonical_url = $url_parts["path"] . (!empty($url_parts["query"]) ? "?" . $url_parts["query"] : "");
        $message = $http_method . "\n" . $canonical_url . "\n" . $timestamp . "\n" . $nonce . "\n" . $body . "\n";
        openssl_sign($message, $raw_sign, $mch_private_key, "sha256WithRSAEncryption");
        $sign = base64_encode($raw_sign);
        $schema = "WECHATPAY2-SHA256-RSA2048";
        $token = sprintf("mchid=\"%s\",nonce_str=\"%s\",timestamp=\"%d\",serial_no=\"%s\",signature=\"%s\"", $merchant_id, $nonce, $timestamp, $serial_no, $sign);
        return $token;
    }
}

?>